//
//  HomeViewController.m
//  TestApplication
//
//  Created by Hanlingyu on 16/8/29.
//  Copyright © 2016年 ltq. All rights reserved.
//

#import "HomeViewController.h"
#import "StarredChannelsTableViewCell.h"
#import "AFNetworking.h"
#import "TAMacro.h"
#import "HomeJoin.h"
#import "HomeContent.h"
#import "HomeRootModel.h"
#import "HomeChannels.h"


#import "NewActionChannel.h"
#import "NewActionContent.h"
#import "NewActionImg.h"
#import "NewActionRootModelOfStarredChannels.h"
#import "NewActionTagModel.h"

#import "PayAttentionToTheDynamicTableViewCell.h"
#import "SelfSizeTool.h"

#import "HomeChannelDetailViewController.h"
#import "MJRefresh.h"
@interface HomeViewController ()
<
    UITableViewDataSource,
    UITableViewDelegate
>
@property (nonatomic, strong) UITableView *homeTableView;
@property (nonatomic, copy) NSString *pid;
@property (nonatomic, copy) NSString *time;

@property (nonatomic, strong) HomeRootModel *getChannelsModel;
// 命名不能已new, copy开头否则会出现错误
// property follows cocoa naming convention for returning 'owned' objects
@property (nonatomic, strong) NewActionRootModelOfStarredChannels *rootModelOfNewAction;
@property (nonatomic, strong) UIImageView *barImageView;

@property (nonatomic, assign) CGFloat cellHeightOfFirst;
@property (nonatomic, assign) CGFloat cellHeightOfSecond;
@property (nonatomic, assign) CGFloat cellHeightOfThird;
@property (nonatomic, assign) CGFloat cellHeightOfFourth;
@property (nonatomic, assign) CGFloat cellHeightOfFifth;
@property (nonatomic, assign) CGFloat cellHeightOfSixth;


@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 首次网络请求
    [self netWork];
    // 创建导航栏
    [self handleNavigationBar];
    // 创建tableView
    [self createTableView];
    // 下拉刷新
    [self refreshNew];
    // 上拉加载
    [self refreshMore];
    
}

- (void)refreshNew {
    self.homeTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self netWork];
    }];
    // 马上进入刷新状态
    [self.homeTableView.mj_header beginRefreshing];
}


- (void)refreshMore {
    self.homeTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self postMoreData];
    }];
}

- (void)endRefresh {
    [self.homeTableView.mj_header endRefreshing];
    [self.homeTableView.mj_footer endRefreshing];
}

- (void)netWork {
    [self hanleHomePageData];
    [self hanleHomePageNewActionData];
    
}



- (void)hanleHomePageData {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    NSString *secParameters = @"c=Feed&m=getStarredChannels&p=%7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%7D&t=t&v=v105";
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return secParameters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:secParameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.getChannelsModel = [HomeRootModel modelWithDic:responseObject];
//        [self.homeTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
}

- (void)hanleHomePageNewActionData {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    NSString *secParameters = @"c=Feed&m=getFeedList&p=%7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%7D&t=t&v=v105";
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return secParameters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:secParameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self endRefresh];
        self.rootModelOfNewAction = [NewActionRootModelOfStarredChannels modelWithDic:responseObject];
        self.pid =  _rootModelOfNewAction.content.lastObject.ID;
        self.time = [NSString stringWithFormat:@"%ld", _rootModelOfNewAction.content.lastObject.createdAt];
        NSLog(@"%@", _pid);
//        NSLog(@"%@", _rootModelOfNewAction.content);
        [_homeTableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
}

- (void)postMoreData {
    
    // 取到当前时间的时间戳
//    NSDate *now = [NSDate date];
//    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[now timeIntervalSince1970]];
//    
    // 用户id
    NSString *userid = @"57c01d33a9a36d0621c123f7";
    
    NSString *pid = _pid;
    
    
    NSString *text = [NSString stringWithFormat:@"{\"uid\":\"%@\",\"pid\":\"%@\",\"timestamp\":%@}", userid, pid, _time];

    NSString *utf8Text = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
    NSString *parmeters = [NSString stringWithFormat:@"c=Feed&m=getFeedList&p=%@&t=t&v=v105", utf8Text];
    NSLog(@"%@", parmeters);
    // c=Feed&m=getFeedList&p=%7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%2C%22pid%22%3A%2257de93f9a9a36db7041dac12%22%2C%22timestamp%22%3A1474519017%7D&t=t&v=v105
    
    // c=Feed&m=getFeedList&p=%7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%2C%22pid%22%3A%2257de93f9a9a36db7041dac12%22%2C%22timestamp%22%3A1474381816%7D&t=t&v=v105
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parmeters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self endRefresh];
        for (NSDictionary *dic in responseObject[@"content"]) {
            NewActionContent *newAction = [NewActionContent modelWithDic:dic];
            [self.rootModelOfNewAction.content addObject:newAction];
        }
        NSLog(@"%ld", self.rootModelOfNewAction.content.count);
        self.pid = self.rootModelOfNewAction.content.lastObject.ID;
        self.time = [NSString stringWithFormat:@"%ld", _rootModelOfNewAction.content.lastObject.createdAt];

        [_homeTableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (_getChannelsModel.content.channels.count == 0) {
            return 0;
        } else if (_getChannelsModel.content.channels.count == 1) {
            return 70;
        } else if (_getChannelsModel.content.channels.count == 2) {
            return 130;
        } else  if (_getChannelsModel.content.channels.count == 3){
            return 200;
        } else {
            return 240;
        }
    } else {
        CGFloat height = [self handleHeight:indexPath];
        return height;
    }
}


- (CGFloat)handleHeight:(NSIndexPath *)indexPath {
    
    self.cellHeightOfFirst = 102;
    NewActionImg *actionImg = _rootModelOfNewAction.content[indexPath.row].img[0];
    CGFloat scale = actionImg.w / (SCREEN_WIDTH - 20);
    self.cellHeightOfSecond = ceilf(actionImg.h / scale);
    if ([_rootModelOfNewAction.content[indexPath.row].desc isEqualToString:@""]) {
        self.cellHeightOfThird = 0;
    } else {
        CGFloat height = [SelfSizeTool selfSizeHeightWithString:_rootModelOfNewAction.content[indexPath.row].desc width:SCREEN_WIDTH - 40 font:[UIFont systemFontOfSize:14]];
//        NSLog(@"%lf", height);
        self.cellHeightOfThird = height + 25;
    }
    if (_rootModelOfNewAction.content[indexPath.row].tag.count != 0) {
        NSMutableArray *tagNameArray = [NSMutableArray array];
        for (NSInteger i = 0; i < _rootModelOfNewAction.content[indexPath.row].tag.count; i++) {
            [tagNameArray addObject:_rootModelOfNewAction.content[indexPath.row].tag[i].content];
        }
        [tagNameArray insertObject:@"#" atIndex:0];
        NSString *tagString = [tagNameArray componentsJoinedByString:@" "];
        CGFloat height = [SelfSizeTool selfSizeHeightWithString:tagString width:SCREEN_WIDTH - 40 font:[UIFont systemFontOfSize:13]];
//        NSLog(@"%lf", height);
        self.cellHeightOfFourth = height + 20;
    } else {
        self.cellHeightOfFourth = 0;
    }
    self.cellHeightOfFifth = 50.0f;
    if (_rootModelOfNewAction.content[indexPath.row].hotComments.count == 0) {
        self.cellHeightOfSixth = 0;
    } else if (_rootModelOfNewAction.content[indexPath.row].hotComments.count > 3) {
        self.cellHeightOfSixth = 80;
    } else {
        self.cellHeightOfSixth = _rootModelOfNewAction.content[indexPath.row].hotComments.count * 20 + 20;
    }

    
    return _cellHeightOfFirst + _cellHeightOfSecond + _cellHeightOfThird + _cellHeightOfFourth + _cellHeightOfFifth + _cellHeightOfSixth;
}

// 处理navigationBar
- (void)handleNavigationBar {
    
    [self createNavigationBarImageView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(SCREEN_WIDTH - 40, 27, 30, 30);
    [button setImage:[UIImage imageNamed:@"createPost"] forState:UIControlStateNormal];
    [self.backView addSubview:button];
    
}

- (void)createNavigationBarImageView {
    UIImageView *barImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 70, 20)];
    barImageView.center = CGPointMake(self.view.frame.size.width / 2, 42);
    barImageView.image = [UIImage imageNamed:@"Young"];
    self.barImageView = barImageView;
    [self.backView addSubview:_barImageView];
}

- (void)createTableView {
    
    self.homeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStylePlain];
    [self.view addSubview:_homeTableView];
    _homeTableView.backgroundColor = [UIColor colorWithWhite:0.917 alpha:1];
    _homeTableView.delegate = self;
    _homeTableView.dataSource = self;
    [_homeTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
    [_homeTableView registerClass:[StarredChannelsTableViewCell class] forCellReuseIdentifier:@"starredChannelsCellReuse"];
    [_homeTableView registerClass:[PayAttentionToTheDynamicTableViewCell class] forCellReuseIdentifier:@"payAttentionToTheDynamicTableViewCellReuse"];
     _homeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return _rootModelOfNewAction.content.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    backView.backgroundColor = [UIColor colorWithWhite:0.917 alpha:1];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 15, SCREEN_WIDTH - 40, 35)];
    [backView addSubview:titleLabel];
    titleLabel.textColor = [UIColor grayColor];
    titleLabel.font = [UIFont systemFontOfSize:14];
    if (section == 0) {
        titleLabel.text = _getChannelsModel.content.title;
    } else {
        titleLabel.text = _rootModelOfNewAction.content[0].title;
    }
    return backView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        StarredChannelsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"starredChannelsCellReuse"];
        cell.homeChannelsArray = _getChannelsModel.content.channels;
        return cell;
    }
    
    PayAttentionToTheDynamicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"payAttentionToTheDynamicTableViewCellReuse"];
    __weak typeof(self) weakSelf = self;
    HomeChannelDetailViewController *homeChannelDetailViewController = [[HomeChannelDetailViewController alloc] init];
// 点击方法的block, 并且给下一页面传递有用的值
    cell.testBlock = ^(NSString *ID){
//        NSLog(@"%@", ID);
        [weakSelf.navigationController pushViewController:homeChannelDetailViewController animated:YES];
//        weakSelf.tabBarController.tabBar.hidden = YES;
        homeChannelDetailViewController.contentArray = _rootModelOfNewAction.content;
        homeChannelDetailViewController.currentIndexPath = indexPath;
    };
    cell.contentOfNewAction = _rootModelOfNewAction.content[indexPath.row];
    return cell;
}



- (void)viewWillDisappear:(BOOL)animated {
//    [self.barImageView removeFromSuperview];
    self.barImageView.hidden = YES;
    
}

- (void)viewWillAppear:(BOOL)animated {
    self.barImageView.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;

//    [self.navigationController.navigationBar addSubview:_barImageView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y <= sectionHeaderHeight&&scrollView.contentOffset.y >= 0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
